import { localCache } from "@/utils/storage";
import { defineStore } from "pinia";
import type { RouteRecordRaw } from "vue-router";

export interface MenuRecord {
  redirect?: any;
  name: string;
  label: string;
  meta: any;
  children?: MenuRecord[];
}

// 菜单数据转化
const transMenus = (routes: RouteRecordRaw[]): MenuRecord[] => {
  const result: MenuRecord[] = [];
  routes.forEach((o) => {
    const { name, children } = o;
    // 1. hidden为true的隐藏
    if (!(o.meta && o.meta.hidden)) {
      // 2. 有子路由时，对子路由进行递归处理
      if (children && children.length) {
        o.children = transMenus(children) as unknown as RouteRecordRaw[];
      }
      // 3. 如果只有一个子菜单，仅展示父级菜单，key为子菜单数据
      let flagName = "";
      if (o.children && o.children.length === 1) {
        flagName = o.children[0].name as string;
      }
      result.push({
        name: flagName ? flagName : (name as string),
        label: o.meta && o.meta.label ? o.meta.label : "",
        // icon: o.meta && o.meta.icon ? o.meta.icon : "",
        meta: o.meta,
        children: flagName ? [] : (o.children as unknown as MenuRecord[]),
      });
    }
  });
  return result;
};
export const menuStore = defineStore("menuStoreName", {
  state: () => {
    return {
      title: import.meta.env.VITE_APP_TITLE, //系统标题
      menus: [] as MenuRecord[], //菜单数据
      openMenu: [] as string[],
      selectedMenu: "",
      isCollapse: false, // 展开收起
      breadcrumbList: [""],
    };
  },
  getters: {
    getMenus(state) {
      return state.menus;
    },
  },
  actions: {
    setSelectedMenu(menu: string = "") {
      this.selectedMenu = menu;
      localCache.setCache("selectedMenu", menu);
    },
    generateMenus(routes: RouteRecordRaw[]) {
      const menus = transMenus(routes); // 转换路由
      this.setMenus(menus);
    },
    setMenus(menus: MenuRecord[]) {
      this.menus = menus;
    },

    setOpenMenu(menus: string[] = []) {
      this.openMenu = menus;
      localCache.setCache("openMenu", menus);
    },
    // 展开收起状态
    updateCollapse() {
      this.isCollapse = !this.isCollapse;
    },
    // 保存选中路径
    SET_BREADCRUMB(data: any) {
      localCache.setCache("breadcrumbList", data);
      this.breadcrumbList = data;
    },
    clearMenus() {
      this.menus = [] as MenuRecord[]; //菜单数据
    },
  },
  share: {
    enable: true,
    initialize: true,
  },
});
